<template>
  <div class="main-box">
    <TableTree label="deptName" :data="treeFilterData" @change="changeTreeFilter">
      <template #operate>
        <el-space alignment="stretch">
          <SButton :buttonProps="{ type: 'primary' }" buttonText="新增" @click="addOrganize" />
          <SButton buttonText="导入" />
          <SButton buttonText="导出" />
        </el-space>
      </template>
    </TableTree>
    <div class="table-box">
      <ProTable ref="proTable" row-key="id" :indent="20" :columns="columns" :request-api="getOrganizeList"
        :init-param="initParam" :search-col="5" data-key="userPageListVoList">
        <!-- 表格 header 按钮 -->
        <template #tableHeader="scope">
          <SButton :buttonProps="{ type: 'primary' }" buttonText="添加" />
          <SButton :buttonProps="{}" buttonText="移除" @click="removeUser(scope)" />
          <SButton :buttonProps="{}" buttonText="导入" />
          <div style="padding-top: 5px;">
            <span>已选择：<a class="a-color">n 条数据</a></span>
          </div>
        </template>
        <!-- 表格操作 -->
        <template #operation="scope">
          <SButton :buttonProps="{ type: 'primary', link: true }" buttonText="设为管理员" />
          <SButton :buttonProps="{ type: 'primary', link: true }" buttonText="移除" @click="handleRemove(scope.row)" />
        </template>
      </ProTable>
    </div>

    <AddOrganize ref="addOrganizeDialogRef" v-model="addOrganizeVisible" :dialogVisible="addOrganizeVisible"
      :title="organizeTitle" :treeFilterData="treeFilterData" @close="addOrganizeVisible = false"
      @confirm="handleAddOrganizeOk" />
  </div>
</template>

<script setup lang="tsx" name="treeProTable">
import { computed, onMounted, reactive, ref } from "vue";
import { User } from "@/api/interface";
import { genderType } from "@/utils/dict";
import ProTable from "@/components/ProTable/index.vue";
// import TableTree from "@/components/TableTree/index.vue";
import TableTree from "./modules/TableTree.vue"
import UserDrawer from "@/views/proTable/components/UserDrawer.vue";
import { ColumnProps, ProTableInstance } from "@/components/ProTable/interface";
import { editUser, addUser } from "@/api/modules/user";
import { getOrganizeList, getOrganicTree, removeOrganizeUser, deleteOrganize } from "@/api/modules/organize";
import SButton from "@/components/SButton/index.vue";
import AddOrganize from "./modules/AddOrganize.vue";
import { ElMessage, ElMessageBox } from "element-plus";
import { useDataStore } from '@/stores/modules/data'
import { remove } from "nprogress";

onMounted(() => {
  getTreeFilter();
});

const dataStore = useDataStore()

// ProTable 实例
const proTable = ref<ProTableInstance>();

// 如果表格需要初始化请求参数，直接定义传给 ProTable(之后每次请求都会自动带上该参数，此参数更改之后也会一直带上，改变此参数会自动刷新表格数据)
const initParam = reactive<any>({ deptId: undefined });

// 获取 treeFilter 数据
// 当 proTable 的 requestAuto 属性为 false，不会自动请求表格数据，等待 treeFilter 数据回来之后，更改 initParam.departmentId 的值，才会触发请求 proTable 数据
const treeFilterData = ref<any>([]);
const getTreeFilter = async () => {
  const res = await getOrganicTree();
  treeFilterData.value = res;
};

const getTableList = (params: any) => {
  return getOrganizeList(params);
};

// 树形筛选切换
const changeTreeFilter = (val: string) => {
  initParam.deptId = val
};

// 模拟远程加载性别搜索框数据
const loading = ref(false);
const filterGenderEnum = ref<typeof genderType>([]);
const remoteMethod = (query: string) => {
  filterGenderEnum.value = [];
  if (!query) return;
  loading.value = true;
  setTimeout(() => {
    loading.value = false;
    filterGenderEnum.value = genderType.filter(item => item.label.includes(query));
  }, 500);
};

onMounted(async () => {
  await dataStore.fetchRoleList();
  await dataStore.fetchDepartmentList()
});

const roleList = computed(() => dataStore.roleList);
const departmentList = computed(() => dataStore.departmentList);
console.log(departmentList.value);


// 表格配置项
const columns = reactive<ColumnProps<any>[]>([
  { type: "selection", fixed: "left", width: 70 },
  { prop: "username", label: "姓名", search: { el: "input" } },
  { prop: "phoneNumber", label: "手机号", search: { el: "input" } },
  {
    prop: "roleName", label: "角色", search: { el: "select", key: "roleId" },
    enum: roleList,
    isFilterEnum: false,
    fieldNames: { label: "roleName", value: "roleId" },
  },
  {
    prop: "deptName", label: "部门", search: { el: "tree-select", props: { filterable: true }, key: "deptId" },
    enum: departmentList,
    isFilterEnum: false,
    fieldNames: { label: "deptName", value: "deptId" },
  },
  { prop: "username", label: "用户名", search: { el: "input" } },
  { prop: "loginName", label: "账号", search: { el: "input" } },
  { prop: "operation", label: "操作" }
]);

// 打开 drawer(新增、查看、编辑)
const drawerRef = ref<InstanceType<typeof UserDrawer> | null>(null);
const openDrawer = (title: string, row: Partial<User.ResUserList> = {}) => {
  const params = {
    title,
    row: { ...row },
    isView: title === "查看",
    api: title === "新增" ? addUser : title === "编辑" ? editUser : undefined,
    getTableList: proTable.value?.getTableList
  };
  drawerRef.value?.acceptParams(params);
};

//新增组织架构
const addOrganizeDialogRef = ref<InstanceType<typeof AddOrganize> | null>(null);
const addOrganizeVisible = ref(false);
const organizeTitle = ref('新增组织架构')
const addOrganize = () => {
  addOrganizeVisible.value = true
};

const handleAddOrganizeOk = async () => {
  addOrganizeVisible.value = false;
  await getTreeFilter();
  proTable.value?.getTableList();
};

//移除用户
const handleRemove = (row: any) => {
  ElMessageBox.confirm("确定移除该用户？", "提示", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
  }).then(() => {
    removeOrganizeUser(row.id).then(() => {
      ElMessage.success("移除用户成功");
      proTable.value?.getTableList();
    })
  })
};

//移除用户
const removeUser = (scope: any) => {
  console.log(scope.selectedListIds);
  if (scope.selectedListIds.length == 0) {

    ElMessage({
      message: '请选择数据！',
      type: 'warning',
      duration: 1500,
    });
    return;
  } else {
    ElMessageBox.confirm("确定移除该用户吗吗？", "提示", {
      confirmButtonText: "确定",
      cancelButtonText: "取消",
      type: "warning",
    }).then(async () => {
      await removeOrganizeUser(scope.selectedListIds);
    }).catch(() => {
      ElMessage.info("移除已取消");
    });
  }
}

</script>
